<template>
	<view v-if="info" class="page">
		<view class="head_bar">
			<view class="main">{{ info.state_name }}</view>
			<view class="desc">{{
                    [
                        '订单已取消',
                        info.pay_type === 3
                            ? '线下支付成功，后台审核中，如有疑问请联系客服！'
                            : '等待买家付款',
                        '等待商家发货',
                        '等待买家收货',
                        '订单已完成',
                    ][info.state]
                }}
			</view>
		</view>
		<!-- <view class="head_bar">
			<view class="status">{{info.state_name}}</view>
			<view class="des">
				{{
	                    [
	                        '订单已取消',
	                        '等待买家付款',
	                        '等待商家发货',
	                        '等待买家收货',
	                        '订单已完成',
	                    ][info.state]
	                }}
			</view>
			<image :src="[
	                        img_refund,
	                        img_dfk,
	                        img_dfh,
	                        img_dsh,
	                        img_ywc,
						][info.state]" class="bg" />
		</view> -->
		<view class="address_info">
			<image :src="info.delivery === 1 ? img_kd : img_zt" class="icon" />
			<view class="right_content">
				<view class="top one-line">
					<text>{{ info.delivery === 1 ? info.shr_name : info.shop_name }}</text>
					<text class="tel">
						{{ info.delivery === 1 ? info.shr_tel : '' }}
					</text>
				</view>
				<view class="address">
					{{ info.province + info.city + info.area + info.shr_address }}
				</view>
			</view>
		</view>
		<view class="goods_info container">
			<view class="label">商品详情</view>
			<view v-for="good in info.goods" :key="good.goods_id" class="good">
				<goods image_width="72px" image_height="72px" :image="imgHost + good.pic" :name="good.goods_title"
					:sub_name="good.goods_sub_title" :price_integer="good._integer" :price_decimal="good._decimal"
					:num="good.buy_num"></goods>
			</view>
		</view>
		<view class="total_bar">
			<view class="list">
				<view class="label">合计数量</view>
				<view class="value">{{ sum }}</view>
			</view>
			<view class="list">
				<view class="label">合计金额</view>
				<view class="value special">￥{{ info.payment }}</view>
			</view>
		</view>
		<view class="order_info">
			<view class="title">订单信息</view>
			<view class="item"> 订单状态：{{ info.state_name }} </view>
			<view class="item">订单编号：{{ info.order_no }}</view>
			<view class="item">支付金额：￥{{ info.payment }}</view>
			<view class="item">支付方式：{{ info.pay_type_name }}</view>
			<view class="item">配送方式：{{ info.delivery_name }}</view>
			<view class="item">创建时间：{{ info.create_at }}</view>
			<template v-if="info.state > 1">
				<view class="item">付款时间：{{ info.pay_time }}</view>
				<view v-if="info.state === 2 && info.fh_time" class="item">发货时间：{{ info.fh_time }}</view>
				<view v-if="info.state === 4 && info.wc_time" class="item">完成时间：{{ info.wc_time }}</view>
			</template>
			<template v-if="info.state === 0">
				<view class="item">取消时间：{{ info.cancel_time }}</view>
				<view class="item">取消原因：{{ info.cancel_remark }}</view>
				<view class="item">取消方式：{{ ['', '后台取消', '自主取消'][info.cancel_type] }}</view>
			</template>
			<view v-if="info.source_name" class="item">订单来源：{{ info.source_name }}</view>
		</view>
		<template v-if="info.delivery === 1 && (info.state === 3 || info.state === 4)">
			<view v-for="item in logisticsInformation" :key="item.ol_id" class="order_info logistics">
				<view class="title">物流信息</view>
				<view class="item">快递公司：{{ item.kd_company }}</view>
				<view class="item">快递单号：{{ item.kd_num }} <text style="color: #FF7800;font-size: 12px;vertical-align:top" @click="copyTextToClipboard(item.kd_num)">【复制单号】</text></view>
			</view>
		</template>

		<fixed-bar v-if="info.state === 1 || info.state === 3">
			<div class="fixed_c">
				<div>
					<span>合计：</span>
					<span class="special">￥</span>
					<span class="special num">{{ info.payment }}</span>
				</div>
				<div class="button_c">
					<template v-if="info.state === 1">
						<view @click="onCancel" hover-class="tapstate" class="button center">
							取消订单
						</view>
						<view @click="showPayPopup(true)" hover-class="tapstate" class="button center">
							继续支付
						</view>
					</template>
					<template v-if="info.state === 3">
						<view @click="onReceiving" hover-class="tapstate" class="button center">
							确认收货
						</view>
					</template>
				</div>
			</div>
		</fixed-bar>
	</view>
	<!--取消订单原因弹出层-->
	<uni-popup ref="inputDialog" type="dialog">
		<uni-popup-dialog before-close mode="input" title="您确定取消该订单吗？" placeholder="请输入取消原因" @confirm="confirmCancel"
			@close="closeConfirmCancel">
		</uni-popup-dialog>
	</uni-popup>
	<!--支付方式选择弹出层-->
	<uni-popup ref="payMethosdPopupInstance" type="bottom" :safe-area="false">
		<view class="choose_pay_methods">
			<view class="closeable" hover-class="hover" @click="showPayPopup(false)">
				<uni-icons type="closeempty" size="20"></uni-icons>
			</view>
			<view class="title">请选择支付方式</view>
			<view v-if="enablePayWay.includes('1')" @click="onPayMethodSelect(2)" class="item" hover-class="tapstate">
				微信支付</view>
			<view v-if="enablePayWay.includes('2')" @click="onPayMethodSelect(3)" class="item" hover-class="tapstate">
				线下支付</view>
			<view v-if="enablePayWay.includes('5')" @click="onPayMethodSelect(5)" class="item" hover-class="tapstate">
				余额支付</view>
			<view class="brace"></view>
			<view class="cancel" @click="showPayPopup(false)" hover-class="tapstate">取消</view>
			<view class="env"></view>
		</view>
	</uni-popup>
</template>

<script setup>
	import { ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import request from '../../utils/common/request';
	import { sleep } from '@/utils/common/index';
	import img_zt from '/static/image/order-zt.png';
	import img_kd from '/static/image/order-kd.png';

	// #ifdef H5
	import { wechatyPay } from '@/utils/h5/index';
	// #endif
	import { useGetThemColor } from '@/hooks/useGetThemColor';

	const { primaryColor, secondaryColor } = useGetThemColor();
	const { imgHost } = getApp().globalData;

	let order_id = '';
	let index = '';
	onLoad((option) => {
		order_id = option.id;
		index = option.index;
		getDetail();
	});

	let info = ref(null);
	const sum = ref(0);
	const getDetail = () => {
		request({
			url: '/api/uorderdetail',
			loadingTip: '加载中',
			data: {
				order_id,
			},
		}).then((res) => {
			if (res.state == -1) res.state = 0;
			let total_sum = 0;
			res.goods.forEach((good) => {
				[good._integer, good._decimal] = good.present_price.split('.');
				total_sum += Number(good.buy_num);
			});
			info.value = res;
			sum.value = total_sum;

			if (res.state > 2) {
				getLogisticsInformation();
			}
		});
	};

	// * 取消订单
	const inputDialog = ref();
	const onCancel = () => {
		inputDialog.value.open();
	};
	const confirmCancel = (reason) => {
		if (!reason)
			return uni.showToast({
				title: '请输入取消原因',
				icon: 'none',
			});
		request({
			method: 'POST',
			url: `/api/ucancelorder?order_id=${info.value.order_id}`,
			data: {
				cancel_remark: reason,
			},
		}).then(async () => {
			uni.showToast({
				title: '取消成功',
				icon: 'success',
				mask: true,
			});
			closeConfirmCancel();
			setSpliceIndexStorage(index);
			await sleep(600);
			getDetail();
		});
	};
	const closeConfirmCancel = () => {
		inputDialog.value.close();
	};

	// * 确认收货
	const onReceiving = () => {
		uni.showModal({
			title: '提示',
			content: '您确定已收到商品吗？',
			confirmColor: primaryColor.value,
			success(res) {
				if (res.cancel) return;
				request({
					url: `/api/uordercomplate?order_id=${info.value.order_id}`,
					method: 'POST',
				}).then(async () => {
					uni.showToast({
						title: '收货成功',
						icon: 'success',
						mask: true,
					});
					setSpliceIndexStorage(index);
					await sleep(600);
					getDetail();
				});
			},
		});
	};

	// * 立即支付
	const enablePayWay = ref([]);
	request({
		url: '/api/reqpaytype',
	}).then((res) => {
		enablePayWay.value = res;
	});
	const payMethosdPopupInstance = ref(null);
	const onPayMethodSelect = (type) => {
		request({
			url: '/api/dfkpay',
			method: 'POST',
			loadingTip: '处理中',
			data: {
				order_id: info.value.order_id,
				pay_type: type,
			},
		}).then(async (res) => {
			if (type === 3) { //线下支付
				uni.showToast({
					title: '提交成功，审核中',
					duration: 800,
					mask: true,
				});
				await sleep(800);
				getDetail();
			} else if (type === 5) { //余额支付
				uni.showToast({
					title: '支付成功',
					duration: 800,
					mask: true,
				});
				setSpliceIndexStorage(index);
				await sleep(800);
				getDetail();
			} else if (type === 2) { //微信支付
				wxPay(res);
			}
		});
		showPayPopup(false);
	};

	const showPayPopup = (flag) => {
		flag ? payMethosdPopupInstance.value.open() : payMethosdPopupInstance.value.close();
	};
	const wxPay = (data) => {
		// #ifdef H5
		wechatyPay(data, async (res) => {
			if (res.err_msg == 'get_brand_wcpay_request:ok') {
				uni.showToast({
					title: '支付成功',
					mask: true,
				});
				setSpliceIndexStorage(index);
				await sleep(800);
				getDetail();
			}
			if (res.err_msg == 'get_brand_wcpay_request:cancel') {}
			if (res.err_msg == 'get_brand_wcpay_request:fail') {
				uni.showToast({
					title: '支付失败',
				});
			}
		});
		// #endif
	};

	// * 详情页微信支付成功，确认收货，取消订单成功，返回订单列表时删除订单
	const setSpliceIndexStorage = (index) => {
		uni.setStorageSync('spliceIndex', index.toString());
	};

	//获取物流信息
	const logisticsInformation = ref([]);
	const getLogisticsInformation = () => {
		request({
			url: '/api/ologistics',
			data: {
				order_id,
			},
		}).then((res) => {
			logisticsInformation.value = res.data;
		});
	};
	
	// 复制文本到剪贴板
	const copyTextToClipboard = (text) => {
		uni.setClipboardData({
			data: text,
			success() {
				uni.showToast({
					title: '复制成功',
					icon: 'none',
				});
			},
			fail(){
				uni.showToast({
					title: '复制失败',
					icon: 'none',
				});
			}
		});
	}
	
</script>

<style scoped lang="scss">
	.head_bar {
		padding: 10px 14px 20px;
		text-align: center;
		background-color: #fff;
		border-top-right-radius: 10px;
		border-top-left-radius: 10px;
		color: v-bind(secondaryColor);

		.main {
			font-size: 17px;
			font-weight: bold;
		}

		.desc {
			margin-top: 8px;
			font-size: 12px;
		}
	}

	.address_info {
		margin-bottom: 10px;
		display: flex;
		align-items: center;
		padding: 14px;
		background-color: #fff;
		border-bottom-right-radius: 10px;
		border-bottom-left-radius: 10px;

		.icon {
			width: 42px;
			height: 40px;
		}

		.right_content {
			flex: 1;
			padding-left: 15px;

			.top {
				font-size: 16px;
				font-weight: bold;
				color: #333;
			}

			.tel {
				margin-left: 12px;
			}

			.address {
				margin-top: 10px;
				color: #333333;
			}
		}
	}

	.goods_info {
		padding-bottom: 14px;
		background-color: #fff;
		border-radius: 10px;

		.label {
			padding: 10px 0;
			font-weight: bold;
			border-bottom: 1px solid #f6f6f6;
		}

		.good {
			margin-top: 10px;
		}
	}

	.total_bar {
		margin: 10px 0;
		padding: 12px 14px;
		background-color: #fff;
		border-radius: 10px;

		.list {
			display: flex;
			justify-content: space-between;

			&+.list {
				margin-top: 14px;
			}

			.label {
				color: #666;
			}

			.value {
				font-weight: bold;
			}

			.special {
				color: v-bind(secondaryColor);
			}
		}
	}

	.order_info {
		padding: 13px 14px;
		background-color: #fff;
		border-radius: 10px;

		.title {
			padding-bottom: 10px;
			font-weight: bold;
			color: #000;
		}

		.item {
			color: #999;

			&+.item {
				margin-top: 5px;
			}
		}
	}

	.logistics {
		margin-top: 10px;
	}

	.fixed_c {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: bold;

		.special {
			color: v-bind(secondaryColor);
		}

		.num {
			font-size: 16px;
		}

		.button_c {
			display: flex;

			.button {
				width: 70px;
				height: 30px;
				border-radius: 20px;
				font-size: 13px;
			}

			.button:first-child {
				background-color: #f7f7f7;
				color: #999;
			}

			.button:last-child {
				margin-left: 10px;
				background-color: v-bind(primaryColor);
				color: #fff;
			}
		}
	}

	::v-deep .uni-button-color {
		color: v-bind(primaryColor);
	}

	.choose_pay_methods {
		position: relative;
		border-radius: 20px 20px 0 0;
		background-color: #fff;
		text-align: center;

		.closeable {
			position: absolute;
			right: 14px;
			top: 10px;
		}

		.title {
			padding-top: 12px;
			padding-bottom: 20px;
			font-size: 16px;
			font-weight: bold;
		}

		.item {
			padding: 18px 0;
			border-bottom: 1px solid #f5f5f5;
		}

		.brace {
			height: 8px;
			background-color: #f5f5f5;
		}

		.cancel {
			padding: 20px 0;
			color: #666;
		}
	}
</style>
<style>
	page {
		background-color: #f5f5f5;
	}

	.page {
		position: relative;
		z-index: 1;
	}
</style>